<?php

class Damages_Methods_Request_SendPerpetratorEmail extends Damages_Methods_Request {

  /**
   *
   * @var int 
   */
  public $id;

  /**
   *
   * @var string 
   */
  public $template;

  /**
   *
   * @var int 
   */
  public $templateId;

  public function __construct($params = null) {
    if ($params) {
      parent::__construct($params);
      $this->id = (int) $params->id;
      $this->template = $params->template;
      $this->templateId = $params->templateId;
    }
  }

  public function process() {
    if (!Damages_Auth::getInstance()->checkPermission(array(Damages_Auth::PERMISSION_ADMIN, Damages_Auth::PERMISSION_LS)))
      throw new Damages_Exception_App(Damages_Codes::ACCESS_DENIED);
    $viewDir = Zend_Controller_Front::getInstance()->getModuleDirectory() . '/views/scripts/partials/';
    $carDamage = DamagesCarDamagesQuery::create()->findOneById($this->id);
    $dbTemplate = DamagesEmailTemplatesQuery::create()->findOneById($this->templateId);
    $estimatedBudget = DamagesEstimatedBudgetsQuery::create()
            ->filterByCarDamageId($this->id)
            ->filterByIsDefault(1)
            ->findOne();
    if (!$estimatedBudget)
      throw new Damages_Exception_App(Damages_Codes::SEND_EMAIL_NO_DEFAULT_EST_BUDGET);
    $this->validate($carDamage);
    $view = new Zend_View();

    $view->setScriptPath($viewDir);
    $view->carDamage = $carDamage;
    $view->estimatedBudget = $estimatedBudget;
    $view->language = $dbTemplate->getLanguage();
    $view->getNameMethod = $dbTemplate->getLanguage() != 'pl' ? sprintf('getName%s', ucfirst($dbTemplate->getLanguage())) : 'getName';
    $this->template = nl2br($this->template);
    foreach (Damages_Tags::getInstance()->getList() as $value) {
      if (preg_match(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $this->template)) {
        $data = $view->render($value->code . '.phtml');
        $this->template = preg_replace(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $data, $this->template);
      }
    }
    Damages_Emails::addEmail($this->id, $this->templateId, $this->template, $carDamage->getDictPerpetrators()->getEmail());
    if (!$carDamage->getPerpetratorReportDate()) {
      $carDamage->setPerpetratorReportDate(time());
      $carDamage->save();
    }
    $response = new Damages_Methods_Response_SendPerpetratorEmail(true);
    $response->setPerpetratorReportDate($carDamage->getPerpetratorReportDate());
    return $response;
  }

  private function validate(DamagesCarDamages $carDamage) {
    if (!$carDamage->getLsId())
      throw new Damages_Exception_App(Damages_Codes::NOTIFICATION_ERROR_NO_LS);
  }

}